package com.imooc.distributedemo.resume.leetcode;

public class SolutionBinaryTreeTraversals {

    // 前序遍历：根-左-右
    public void preorderTraversal(TreeNode root) {
        if (root == null) return;
        System.out.print(root.val + " ");
        preorderTraversal(root.left);
        preorderTraversal(root.right);
    }

    // 中序遍历：左-根-右
    public void inorderTraversal(TreeNode root) {
        if (root == null) return;
        inorderTraversal(root.left);
        System.out.print(root.val + " ");
        inorderTraversal(root.right);
    }

    // 后序遍历：左-右-根
    public void postorderTraversal(TreeNode root) {
        if (root == null) return;
        postorderTraversal(root.left);
        postorderTraversal(root.right);
        System.out.print(root.val + " ");
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);

        SolutionBinaryTreeTraversals traversals = new SolutionBinaryTreeTraversals();

        System.out.println("Preorder traversal: ");
        traversals.preorderTraversal(root);

        System.out.println("\nInorder traversal: ");
        traversals.inorderTraversal(root);

        System.out.println("\nPostorder traversal: ");
        traversals.postorderTraversal(root);
    }
}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }
}
